﻿using AWSV2.Models;
using System;
using System.Configuration;
using System.Net;
using System.Net.Sockets;
using System.Speech.Synthesis;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
using Common.Utility;

namespace AWSV2.Services
{
    public static class TTSHelper
    {
        private static readonly log4net.ILog log = LogHelper.GetLogger();

        

        private static Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        private static readonly AppSettingsSection _mainSetting = SettingsHelper.AWSV2Settings;

        private static readonly SpeechSynthesizer _speaker = new SpeechSynthesizer
        {
            Volume = 100,
            Rate = Convert.ToInt32(_mainSetting.Settings["SpeechSpeed"]?.Value ?? "0")
        };

        private static Prompt _prompt;

        public static Prompt TTS(WeighingRecordModel wrm, string text)
        {
            try
            {
                
                if (_prompt == null || _prompt.IsCompleted)
                {
                    _speaker.SpeakAsync(Replace(wrm, text));
                }
                
                return _prompt;
            }
            catch (Exception ex)
            {
                log.Info($"TTSHelper.TTS error:" + ex.Message);
                return null;
            }
        }

        public static void TTS1(WeighingRecordModel wrm, string text)
        {
            try
            {
                var lprConfig = Common.Utility.SettingsHelper.ZXLPRSettings.Settings;
                //如果是网络继电器启用了，那么就用网络继电器的语音
                if (lprConfig["Relay2IP"] != null &&
                    lprConfig["Relay2Enable"] != null &&
                    lprConfig["Relay2Enable"].Value == "1")
                {
                    if (!socket.Connected)
                        socket.Connect(new IPEndPoint(IPAddress.Parse(lprConfig["Relay2IP"].Value), 6000));

                    int channel = 1;
                    string str = Replace(wrm, text);
                    var bts = Encoding.GetEncoding("GB2312").GetBytes(str);
                    string content = $"AT+TTS{channel}=1,0,1,0,{bts.Length}\r\n{str}";

                    if (socket.Connected)
                    {
                        bts = Encoding.GetEncoding("GB2312").GetBytes(str);
                        socket.Send(bts);
                    }
                }
                else
                {
                    SpeechSynthesizer speaker = new SpeechSynthesizer();
                    speaker.Rate = Convert.ToInt32(_mainSetting.Settings["SpeechSpeed"]?.Value ?? "0");
                    string str = Replace(wrm, text);
                    speaker.SpeakAsync(str);

                }

            }
            catch (Exception ex)
            {
                log.Info($"TTSHelper.TTS error:" + ex.Message);
            }
        }

        public static string Replace(WeighingRecordModel wrm, string text)
        {
            string unit = _mainSetting.Settings["WeighingUnit"]?.Value ?? string.Empty;
            unit = string.IsNullOrEmpty(unit) ? "千克" : unit.ToLower() == "kg" ? "千克" : "吨";
            //string ch = Regex.Replace(wrm.Ch, ".", "$0 ");
            string ch = Regex.Replace(wrm.Ch ?? string.Empty, ".", "$0");
            return text.Replace("%kh%", wrm.Kh).Replace("%ch%", TTSNumberRead(ch)).Replace("%wz%", wrm.Wz).
                  Replace("%mz%", wrm.Mz).Replace("%pz%", wrm.Pz).Replace("%jz%", wrm.Jz).
                  Replace("%kz%", wrm.Kz).Replace("%kl%", wrm.Kl).Replace("%sz%", wrm.Sz).
                  Replace("%by1%", wrm.By1).Replace("%by2%", wrm.By2).Replace("%by3%", wrm.By3).Replace("%by4%", wrm.By4).
                  Replace("%by5%", wrm.By5).Replace("%by6%", wrm.By6).Replace("%by7%", wrm.By7).Replace("%by8%", wrm.By8).
                  Replace("%by9%", wrm.By9).Replace("%by10%", wrm.By10).Replace("%by11%", wrm.By11).Replace("%by12%", wrm.By12).
                  Replace("%by13%", wrm.By13).Replace("%by14%", wrm.By14).Replace("%by15%", wrm.By15).Replace("%by16%", wrm.By16).
                  Replace("%by17%", wrm.By17).Replace("%by18%", wrm.By18).Replace("%by19%", wrm.By19).Replace("%by20%", wrm.By20);
                  //Replace("kg", unit).Replace("KG", unit).Replace("t", unit).Replace("T", unit);
        }

        private static string TTSNumberRead(string str)
        {
           
            var cnNums = new string[] { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" }.ToArray();
            var albNums = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }.ToArray();

            foreach (var i in cnNums)
            {

                str = str.Replace(i, $"{i} ");
            }

            foreach (var i in albNums)
            {

                str = str.Replace(i, $"{i} ");
            }
            str = str.Trim().Replace(" ", "");
            return str;
        }
    }
}
